﻿using System;
using System.Linq.Expressions;
using System.Web.Mvc;
using Web7.Container.Services;
using Web7.Core.Security;
using Web7.Container.Models;
using Microsoft.Practices.Unity;

namespace Web7.Container.Controllers
{
    public class RoleController : AdminController
    {

        private IRoleService _RoleService;

        public RoleController(IRoleService roleService)
        {
            _RoleService = roleService;
        }

		[Dependency]
		public IAssistRoleService<Guid> AssistRoleService { get; set; }


        public ActionResult Index(int? page)
        {
            int pageIndex = 1;
            int.TryParse(Request["page"], out pageIndex);

            if (page == null || page <= 0)
            {
                page = 1;
            }
			// TODO: 检查此处逻辑[原有逻辑为 id > 0]
            Expression<Func<Role, bool>> predicate = f => f.Id != Guid.Empty;

            const int pageSize = 10;
            var rolePageList = new PagedList<Role>(_RoleService.Fetch(
                    predicate,
                    p => p.Desc(f => f.Id),
                    (page.Value - 1) * pageSize,
                    pageSize), page.Value, pageSize, _RoleService.Count(predicate));

            return View((PagedList<Role>)rolePageList);
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost, ActionName("Create")]
        public ActionResult CreatePost(RoleViewModel createModel)
        {

			if (ModelState.IsValid)
			{
				var role = AssistRoleService.CreateRole<RoleViewModel>(createModel);

				if(null != role )
				{
					_RoleService.Create(role);
				}
			}
            return RedirectToAction("Index");
        }

		// TODO: remove this debug method
		public ActionResult Bad(string extype)
		{
			switch (extype)
			{
				case "null":
					throw new ArgumentNullException("extype");
				case "notfound":
					throw new System.IO.FileNotFoundException("Your file");
				default:
					throw new Exception("Some custom exception");
			}
		}

    	public ActionResult Edit(Guid id)
        {
			// 读出
			var role = _RoleService.Get(r => r.Id == id);

            return View(role);
        }

        [HttpPost, ActionName("Edit")]
        public ActionResult EditPost(RoleUpdateModel updateData)
        {
			// 更新

			// _RoleService.Update();
			Role role = new Role();
        	role.Id = updateData.Id;
        	role.RoleName = updateData.RoleName;
			_RoleService.Update(role);

            return RedirectToAction("Index");
        }

        
        public ActionResult Delete(Guid id)
        {
			// TODO:改为 POST 请求
			_RoleService.Delete(id);
            return RedirectToAction("Index");
        }
    }
}
